package com.company.emallbackend.utils;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.company.emallbackend.common.AliPayConfig;
import com.company.emallbackend.entity.AliPay;
import com.company.emallbackend.entity.dto.CartDTO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author hljstart
 * @create 2022-10-13-15:31
 */
public class AliPayUtil {

    private static final String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    /**
     * 签名方式
     */
    private static final String SIGN_TYPE = "RSA2";

    /**
     * 得到aliPayConfig
     * @param aliPayConfig
     * @return
     */
    public static AlipayClient getAlipayClient(AliPayConfig aliPayConfig){
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        return alipayClient;
    }
    public static boolean sendRequestToAliPay(AliPayConfig aliPayConfig, AliPay aliPay, HttpServletResponse httpResponse) {
        try {
            // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
            AlipayClient alipayClient = getAlipayClient(aliPayConfig);
            // 2. 创建 Request并设置Request参数
            //发送请求的 Request类
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(aliPayConfig.getNotifyUrl());
            request.setReturnUrl(aliPayConfig.getReturnUrl());
            JSONObject bizContent = new JSONObject();
            // 我们自己生成的订单编号
            bizContent.set("out_trade_no", aliPay.getTradeNo());
            // 订单的总金额
            bizContent.set("total_amount", aliPay.getTotalAmount());
            // 支付的名称
            bizContent.set("subject", aliPay.getSubject());
            // 固定配置
            bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");
            List<CartDTO> cartDTOList = aliPay.getCartDTOList();
            String str="";
            for (CartDTO cartDTO : cartDTOList) {
                Integer productId = cartDTO.getProductId();
                Integer count = cartDTO.getCount();
                str+=productId+","+count+"-";
            }
            bizContent.set("passback_params",str);
            request.setBizContent(bizContent.toString());
            String form = alipayClient.pageExecute(request).getBody();
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            // 直接将完整的表单html输出到页面
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
